package com.ruoyi.alert.config;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.util.HashMap;

@Configuration
public class AppConfig {

    @Bean
    public Queue alarmQueue() {
        return new Queue("alarm.queue", true, false, false,
                new HashMap<String, Object>() {{
                    put("x-message-ttl", 86400000); // 消息存活时间24小时
                    put("x-dead-letter-exchange", "alarm.dead.letter.exchange");
                    put("x-dead-letter-routing-key", "alarm.dead.letter.routingkey");
                }});
    }

    @Bean
    public Queue deadLetterQueue() {
        return new Queue("alarm.dead.letter.queue");
    }
    @Bean
    public DirectExchange deadLetterExchange() {
        return new DirectExchange("alarm.dead.letter.exchange");
    }

    @Bean
    public Binding deadLetterBinding() {
        return BindingBuilder.bind(deadLetterQueue())
                .to(deadLetterExchange())
                .with("alarm.dead.letter.routingkey");
    }

    @Bean
    public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, String> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new StringRedisSerializer());
        return template;
    }

    @Bean
    public MessageConverter jsonMessageConverter() {
        return new Jackson2JsonMessageConverter();
    }

    @Bean
    public RabbitTemplate.ConfirmCallback confirmCallback() {
        return (correlationData, ack, cause) -> {
            if (ack) {
                System.out.println("消息成功发送到Exchange");
            } else {
                System.out.println("消息发送失败: " + cause);
            }
        };
    }
}